<?php

class Product extends CActiveRecord {
    /**
     * The followings are the available columns in table 'www_products':
     * @var integer $id
     * @var integer $node_id
     * @var integer $brand_id
     * @var string $name
     * @var string $standard
     * @var double $market_price
     * @var double $member_price
     * @var double $keywords
     * @var double $tags
     * @var string $summary
     * @var string $picture_saved_path
     * @var string $thumbnail_saved_path
     * @var integer $is_recommend
     * @var integer $status
     * @var integer $created
     * @var integer $updated
     */
     
    private $_oldTags;
    public $clicks_count = 0;


    /**
     * Returns the static model of the specified AR class.
     * @return CActiveRecord the static model class
     */
    public static function model($className=__CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return '{{products}}';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
    // NOTE: you should only define rules for those attributes that
    // will receive user inputs.
        return array(
            array('node_id, name, summary, is_recommend, order_pos, brand_id', 'required'),
            array('node_id, is_recommend, is_picking, status, created, updated, order_pos, clicks_count, inteqral_value, brand_id', 'numerical', 'integerOnly' => true),
            array('is_recommend, is_picking', 'boolean', 'falseValue' => 0, 'trueValue' => 1),
            array('market_price, member_price', 'numerical'),
            array('keywords, tags, name, standard, picture_saved_path, thumbnail_saved_path', 'length', 'max' => 200),
            array('tags', 'match', 'pattern' => '/^[\x00-\xff,]+$/', 'message' => 'Tags can only contain word characters.'),
            array('tags', 'normalizeTags'),
            array('picture_saved_path', 'file', 'on' => 'insert',
                'allowEmpty' => false,
                'types' => 'jpg, jpeg, gif',
                'maxSize' => 1024 * 1024 * 10,
            ),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
    // NOTE: you may need to adjust the relation name and the related
    // class name for the relations automatically generated below.
        return array(
            // 所属节点
            'node' => array(self::BELONGS_TO, 'Node', 'node_id'),
            // 发布用户
            'user' => array(self::BELONGS_TO, 'User', 'user_id'),
            // 评论列表
            'comments' =>  array(self::HAS_MANY, 'ProductComment', 'product_id',
                'condition' => 'products_comments.status = '. ProductComment::STATUS_APPROVED,
                'order' => 'comments.created DESC'
            ),
            // 评论数量
            'commentCount' => array(self::STAT, 'ProductComment', 'product_id',
                'condition' => 'status = ' . ProductComment::STATUS_APPROVED),
            // 所属品牌
            'brand' => array(self::BELONGS_TO, 'MultiLevelCategory', 'brand_id'),
//            'mainBrand' => array(self::BELONGS_TO, 'ProductBrand', 'main_brand_id'),
//            // 所属次品牌
//            'subBrand' => array(self::BELONGS_TO, 'ProductBrand', 'sub_brand_id'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'id' => 'Id',
            'node_id' => Yii::t('common', 'node_id'),
            'keywords' => Yii::t('product', 'keywords'),
            'tags' => Yii::t('product', 'tags'),
            'brand_id' => Yii::t('product', 'brand_id'),
            'name' => Yii::t('product', 'name'),
            'standard' => Yii::t('product', 'standard'),
            'market_price' => Yii::t('product', 'market_price'),
            'member_price' => Yii::t('product', 'member_price'),
            'inteqral_value' => Yii::t('product', 'inteqral_value'),
            'summary' => Yii::t('product', 'summary'),
            'picture_saved_path' => Yii::t('product', 'picture_saved_path'),
            'thumbnail_saved_path' => Yii::t('product', 'thumbnail_saved_path'),
            'is_recommend' => Yii::t('common', 'is_recommend'),
            'is_picking' => Yii::t('common', 'is_picking'),
            'order_pos' => Yii::t('common', 'order_pos'),
            'status' => Yii::t('options', 'status'),
            'created' => Yii::t('common', 'created'),
            'updated' => Yii::t('common', 'updated'),
        );
    }

    // "status" field Icon format
    public function getStatusIconFormat() {
        switch ($this->status) {
            case Options::STATUS_DRAFT:
                $img = 'status_draft.gif';
                break;
            case Options::STATUS_PUBLISHED:
                $img = 'status_published.gif';
                break;
            case Options::STATUS_PENDING_DELETE:
                $img = 'status_pending_delete.gif';
                break;
            default:
                $img = 'status_unknown.gif';
        }
        return CHtml::image(Yii::app()->assetManager->baseUrl . '/backend/images/' . $img);
    }

    // status AJax submit
    public function getStatusAjaxLink() {
        return CHtml::ajaxLink($this->statusIconFormat,
            Yii::app()->createUrl('backend/products/changeStatus'),
            array(
                'type' => 'POST',
                'data' => 'id=' . $this->id,
                'dataType' => 'text',
                'update' => "#status{$this->id}",
            ),
            array('id' => "status{$this->id}")
        );
    }

    // “是否推荐”图标格式
    public function getIsRecommendIconFormat() {
        $img = (intval($this->is_recommend) == Options::RECOMMEND_YES)
            ? 'yes.gif' : 'no.gif';
        return CHtml::image(Yii::app()->baseUrl . '/assets/backend/images/' . $img);
    }

    // change recommend status ajax link
    public function getIsRecommendAjaxLink() {
        return CHtml::ajaxLink($this->isRecommendIconFormat,
            Yii::app()->createUrl('backend/products/changeRecommend'),
            array(
                'type' => 'POST',
                'data' => 'id=' . $this->id,
                'dataType' => 'text',
                'update' => "#recommend{$this->id}",
            ),
            array('id' => "recommend{$this->id}")
        );
    }

    // “是否精品”图标格式
    public function getIsPickingIconFormat() {
        $img = (intval($this->is_picking) == Options::PICKING_YES)
            ? 'yes.gif' : 'no.gif';
        return CHtml::image(Yii::app()->baseUrl . "/assets/backend/images/{$img}");
    }

    // change picking status ajax link
    public function getIsPickingAjaxLink() {
        return CHtml::ajaxLink($this->isPickingIconFormat,
            Yii::app()->createUrl('/backend/products/changePicking'),
            array(
                'type' => 'POST',
                'data' => 'id=' . $this->id,
                'dataType' => 'text',
                'update' => "#picking{$this->id}",
            ),
            array('id' => "picking{$this->id}")
        );
    }

    public function behaviors() {
        return array(
            'CTimestampBehavior' => array(
                'class' => 'zii.behaviors.CTimestampBehavior',
                'createAttribute' => 'created',
                'updateAttribute' => 'updated',
            )
        );
    }

    // "updated" field formatted
    public function getUpdatedFormatted() {
        return ($this->updated) ? date('Y-m-d', $this->updated) : '';
    }

    /**
     * @return array a list of links that point to the post list filtered by every tag of this post
     */
    public function getTagLinks() {
        $links = array();
        foreach (Tag::string2array($this->tags) as $tag) {
            $links[] = CHtml::link(CHtml::encode($tag), array('products/index', 'tag' => $tag));
        }
        return $links;
    }

    /**
     * Normalizes the user-entered tags.
     */
    public function normalizeTags($attribute,$params) {
        $this->tags = Tag::array2string(array_unique(Tag::string2array($this->tags)));
    }

    /**
     * Adds a new comment to this post.
     * This method will set status and post_id of the comment accordingly.
     * @param Comment the comment to be added
     * @return boolean whether the comment is saved successfully
     */
    public function addComment($comment) {
        if (Yii::app()->params['productCommentNeedApproval']) {
            $comment->status = ProductComment::STATUS_PENDING;
        } else {
            $comment->status = ProductComment::STATUS_APPROVED;
        }
        $comment->product_id = $this->id;
        return $comment->save();
    }

    private $_original_picture_saved_path;
    protected function afterFind() {
        parent::afterFind();

        $this->_original_picture_saved_path = $this->picture_saved_path;
        $this->_oldTags = $this->tags;
    }

    protected function beforeSave() {
        parent::beforeSave();

        if (parent::beforeSave()) {
            if ($this->isNewRecord) {
                $this->user_id = Yii::app()->user->id;
            }
        }

        $uploading_file = CUploadedFile::getInstance($this, 'picture_saved_path');
        if (is_object($uploading_file) && get_class($uploading_file) === 'CUploadedFile') {
            if (!$this->isNewRecord) {
                $model = Product::model()->findByPk($this->id);
                @unlink($model->picturePath);
                @unlink($model->thumbnailPath);
            }
            $filename = md5(time() . $this->node_id) . '.' . $uploading_file->getExtensionName();
            $this->picture_saved_path = $filename;
            $uploading_file->saveAs(Yii::app()->basePath . '/../upload/product/' . $filename);
            Yii::import('application.extensions.AppHelper.YImage');
            $this->thumbnail_saved_path = YImage::generateThumbnail("product", $filename);
        } else {
            $this->picture_saved_path = $this->_original_picture_saved_path;
        }
        
        return true;
    }

    /**
     * This is invoked after the record is saved.
     */
    protected function afterSave() {
        parent::afterSave();
        Tag::model()->updateFrequency($this->_oldTags, $this->tags, Tag::TYPE_PRODUCT);
    }

    /**
     * This is invoked after the record is deleted.
     */
    protected function afterDelete() {
        parent::afterDelete();
        @unlink($this->picturePath);
        @unlink($this->thumbnailPath);
//        PostComment::model()->deleteAll('post_id=' . $this->id);
        Tag::model()->updateFrequency($this->tags, '', Tag::TYPE_PRODUCT);
    }

    public function getPicturePath() {
        return Yii::app()->basePath . '/../upload/product/' . $this->picture_saved_path;
    }

    public function getPictureSource() {
        return Yii::app()->baseUrl . '/upload/product/' . $this->picture_saved_path;
    }

    public function getThumbnailPath() {
        return Yii::app()->basePath . '/../upload/product/' . $this->thumbnail_saved_path;
    }

    public function getThumbnailSource() {
        return Yii::app()->baseUrl . '/upload/product/' . $this->thumbnail_saved_path;
    }

    public function getUrl() {
        return Yii::app()->createUrl('products/view', array(
            'id' => $this->id,
            'title' => $this->name,
        ));
    }

    protected function findBase($type = 'recent', $node = null, $limit = 12) {
        $criteria = new CDbCriteria();
        $criteria->condition = 'status = ' . Options::STATUS_PUBLISHED;
        if ($node !== null) {
            if (is_array($node)) {
                $criteria->addInCondition('node_id', $node);
            } else if (is_int($node)) {
                $criteria->addCondition("node_id = {$node}");
            }
        }
        switch ($type) {
            case 'recent':
                $criteria->order = 'created DESC';
                break;
            case 'hot':
                $criteria->order = 'clicks_count DESC';
                break;
            case 'recommend':
                $criteria->addCondition('is_recommend = ' . Options::RECOMMEND_YES);
                break;
            case 'picking':
                $criteria->addCondition('is_picking = ' . Options::PICKING_YES);
                break;
            default:
                $criteria->order = 'created DESC';
                break;
        }
        $criteria->limit = $limit;

        return self::model()->findAll($criteria);
    }

    // 最新信息
    public function findRecent($node = null, $limit = 12) {
        return $this->findBase('recent', $node, $limit);
    }

    // 热门信息
    public function findHot($node = null, $limit = 12) {
        return $this->findBase('hot', $node, $limit);
    }

    //　推荐信息
    public function findRecommend($node = null, $limit = 12) {
        return $this->findBase('recommend', $node, $limit);
    }

    // 置顶信息
    public function findPicking($node = null, $limit = 12) {
        return $this->findBase('picking', $node, $limit);
    }

}